{% extends "grid/base.html" %}

{% load emojificate grid_tags i18n package_tags page_metadata_tags %}

{% block metadata %}
    {% page_metadata page_title=grid.title page_description=grid.description page_keywords=grid.packages.all|join:',' %}
{% endblock metadata %}

{% block javascript %}
    {{ block.super }}
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
    <script src="{{ STATIC_URL }}js/jquery.dataTables.min.js" type="text/javascript"></script>
{% endblock javascript %}

{% block body %}
    <h2 id="grid-name">
        <a href="{% url 'home' %}">home</a> / <a href="{% url 'grids' %}">grids</a> / {{ grid.title }}

        <a href="{% url 'edit_grid' grid.slug %}"><img src="{{ STATIC_URL }}img/icon_changelink.gif" alt="edit" /></a>

    </h2>
    <p>
        {{ grid.description|emojify|emojificate|safe|urlize|linebreaksbr }}
    </p>

    <p id="grid-toggle">&nbsp;</p>
    <p id="grid-classic"><a href="{% url 'grid' grid.slug %}">Standard View</a></p>

    {% if features %}
        <h2>Features currently being evaluated</h2>
        <table id="grid" border="3">
            <thead>
                <tr>
                    <th>Feature</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                {% for feature in features %}
                    <tr>
                        <td>{{ feature.title }}
                            {% if request.user.is_authenticated %}
                                <a href="{% url 'edit_feature' feature.pk %}"><img src="{{ STATIC_URL }}img/icon_changelink.gif" alt="edit" /></a>{% if perms.grid.delete_feature %}&nbsp;<a href="#" id="feature-delete-{{ feature.pk }}"><img src="{{ STATIC_URL }}img/icon_deletelink.gif" alt="delete" /></a>{% endif %}
                            {% endif %}
                        </td>
                        <td>{{ feature.description|wordwrap:80|linebreaksbr }}</td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
        {% if request.user.is_authenticated %}

            <p><img src="{{ STATIC_URL }}img/icon_addlink.gif" />&nbsp;<a href="{% url 'add_feature' grid.slug %}">Add new feature to the grid</a></p>

        {% endif %}
    {% else %}
        {% if request.user.is_authenticated %}

            <p><img src="{{ STATIC_URL }}img/icon_addlink.gif" />&nbsp;<a href="{% url 'add_feature' grid.slug %}">Add a feature to the grid</a></p>

        {% endif %}
    {% endif %}


    {% if grid_packages.exists %}
        {% if request.user.is_authenticated %}
            <p><img src="{{ STATIC_URL }}img/icon_addlink.gif" />&nbsp;<a href="{% url 'add_grid_package' grid.slug %}">Add another package</a></p>
        {% endif %}
        <table id="sortable-table" cellpadding="0" cellspace="0" class="display">
            <thead>
                <tr>
                    <th>Package</th>
                    {% for attribute_name, display_name in attributes %}
                        {% if display_name %}
                            <th>{{ display_name }}</th>
                        {% else %}
                            <th>{{ attribute_name }}</th>
                        {% endif %}
                    {% endfor %}
                    {% for feature in features %}
                        <th>{{ feature.title }}</th>
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                {% for package in grid_packages %}
                    <tr class="{% cycle 'even' 'odd' %}">
                        <td class="package-name"><a href="{% url 'package' package.package.slug %}">{{ package.package.title }}</a>
                            {% if perms.grid.delete_gridpackage %}&nbsp;<a href="#" id="package-delete-{{ package.pk }}"><img src="{{ STATIC_URL }}img/icon_deletelink.gif" alt="delete"/></a>{% endif %}
                        </td>
                        {% for attribute_name, display_name in attributes %}
                            {% if attribute_name == "participant_list" %}
                                <td>
                                    {{ package.package.participant_list|length }}
                                    {% comment %}
                                    {% for collaborator in package.package.participant_list %}
                                        {% if forloop.counter <= 10 %}
                                            <a href="{{ package.package.repo.url }}/{{ collaborator }}">{{ collaborator }}</a>
                                            {% if not forloop.last %}
                                                <br />
                                            {% endif %}
                                        {% endif %}
                                        {% if forloop.counter == 11 %}
                                            <a href="{% url 'package' package.package.slug %}">more...</a>
                                        {% endif %}
                                    {% endfor %}
                                    {% endcomment %}
                                </td>
                            {% else %}
                                {% if attribute_name == "repo" %}
                                    <td><a href="{{ package.package.repo_url }}">{{ package.package.repo }}</a></td>
                                {% else %}
                                    {% with val=attribute_name|style_attribute:package.package %}
                                        <td>{{ val }}</td>
                                    {% endwith %}
                                {% endif %}
                            {% endif %}
                        {% endfor %}
                        {% for feature in features %}
                            {% with element=elements|hash:feature.pk|hash:package.pk %}
                                <td id="element-f{{ feature.pk }}-p{{ package.pk }}">{% if element %}{{ element.text|style_element|safe|urlize|linebreaksbr }}{% endif %}<noscript> <a class="edit" href="{% url 'edit_element' feature.pk package.pk %}">[edit]</a></noscript></td>
                            {% endwith %}
                        {% endfor %}
                    </tr>
                {% endfor %}
            </tbody>
            <tfoot>
                <tr>
                    <th>Package</th>
                    {% for attribute_name, display_name in attributes %}
                        {% if display_name %}
                            <th>{{ display_name }}</th>
                        {% else %}
                            <th>{{ attribute_name }}</th>
                        {% endif %}
                    {% endfor %}
                    {% for feature in features %}
                        <th>{{ feature.title }}</th>
                    {% endfor %}
                </tr>
            </tfoot>
        </table>

        {% if request.user.is_authenticated %}
            <p><img src="{{ STATIC_URL }}img/icon_changelink.gif"/>&nbsp;Highlighted cells are editable.  Click highlighted cells to change text.</p>
        {% endif %}

    {% else %}
        <p><img src="{{ STATIC_URL }}img/icon_addlink.gif" />&nbsp;<a href="{% url 'add_grid_package' grid.slug %}">Add a package to get a grid view</a></p>
    {% endif %}


{% endblock body %}

{% block extra_body %}
    <script type="text/javascript">

        function getParameterByName(name) {
            // short and sweet reading of query-string parameters
            // SEE http://stackoverflow.com/questions/901115/get-querystring-values-with-jquery/5158301#5158301
            var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
            return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
        }

        $(function() {

            // allow user override of fancy JS-grid by adding "?simpleGrid=true" to URL
            var usingSimpleGrid = getParameterByName('simpleGrid') == 'true';
            var toggleURL = window.location.href;
            if (usingSimpleGrid) {
                // just keep the simple table, then set the toggle to reload to a smart grid
                toggleURL = toggleURL.replace('?simpleGrid=true','');
                $('#grid-toggle').html('<a href="'+ toggleURL +'">{% translate "Switch to smart grid" %}</a>');
            } else {
                // set the toggle to reload to a simple table, then build a smart grid
                if (window.location.search.indexOf('simpleGrid=true') === -1) {
                    if (window.location.search === "") {
                        toggleURL = toggleURL + '?simpleGrid=true';
                    } else {
                        toggleURL = toggleURL.replace('?', '?simpleGrid=true&');
                    }
                }
                $('#grid-toggle').html('<a href="'+ toggleURL +'">{% translate "Switch to simple table" %}</a>');


                /* freeze table-column widths before splitting the package grid */

                // capture "natural" widths of all table headers
                var $headers = $('#sortable-table thead th');
                var howManyColumns = $headers.length;
                var $topmostCells = $('#sortable-table tbody tr:first-child td');

                $topmostCells.each(function(index, element) {
                    ///var matchingWidth = $headers.eq(index).width();
                    var matchingWidth = $headers.eq(index).css('width'); // || $headers.eq(index).width();
                    $(this).css('width', matchingWidth);
                });

                // apply dataTable plugin to package grid (will split tables)
                $('#sortable-table').dataTable({
                    // "bScrollInfinite": true,
                    "bSort": false, // disable default sorting
                    "bAutoWidth": true,
                    "sScrollY": "600px",
                    "sScrollX": "100%",
                    //"sScrollXInner": "110%",
                    "bScrollCollapse": true
                });
                // now freeze these widths in all tables!
                // SEE http://www.quirksmode.org/css/tables.html
                $('.dataTables_wrapper table').css('table-layout', 'fixed');

                // reverse IE8-only style hack (to support sticky footer, which we won't need here)
                $('#wrap').css('display','block');
            }

            {% if request.user.is_authenticated %}
                // Handle element edit redirects
                {% for feature in features %}
                    {% for grid_package in grid_packages %}
                        {% with element=elements|hash:feature.pk|hash:grid_package.pk %}

                        {% endwith %}

                        $("td#element-f{{ feature.pk }}-p{{ grid_package.pk }}").click(function() {
                            var url = "{% url 'edit_element' feature.pk grid_package.pk %}";
                            $(location).attr('href',url);
                        });
                    {% endfor %}
                {% endfor %}

                delete_confirmation = function(e, url) {
                    // The deletes are placed in here so there is just one place needed
                    e.preventDefault();

                    if(confirm('Are you sure?')) {
                        window.location = url;
                    }
                };

                // handle feature deletes
                {% if perms.grid.delete_feature %}
                    {% for feature in features %}
                        $("a#feature-delete-{{ feature.pk }}").click(function(e) {
                            delete_confirmation(e, '{% url 'delete_feature' feature.pk %}')
                        });
                    {% endfor %}
                {% endif %}

                {% if perms.grid.delete_gridpackage %}
                    // handle package deletes
                    {% for grid_package in grid_packages %}
                        $("a#package-delete-{{ grid_package.pk }}").click(function(e) {
                            delete_confirmation(e, '{% url 'delete_grid_package' grid_package.pk %}')
                        });
                    {% endfor %}
                {% endif %}

            {% endif %}


            function handleRTD(elements) {
                if (!elements.length){
                    return;
                }
                var ele = $(elements.shift());
                if (!ele){
                    return;
                }
                var slug = ele.attr('rel');
                var url = "http://readthedocs.org/api/v1/build/"+ slug +"/?format=jsonp";
                $.ajax({
                    url: url,
                    dataType: 'jsonp',
                    success:function(data){
                        if (data.objects.length > 0){
                            var href = "http://readthedocs.org/projects/" + slug;
                            var a = "<a href='" + href + "'>Yes</a>";
                            ele.html(a);
                            handleRTD(elements);
                        } else {
                            ele.text("No");
                            handleRTD(elements);
                        }
                    }
                });
            }
            handleRTD($.makeArray($('table#grid span.rtd-status')));
        });
    </script>
{% endblock extra_body %}
